package com.company.restaurant;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.*;

/**
 * Created by User on 13.02.14.
 */
public class Starter {
    private static final Logger logger = LoggerFactory.getLogger(Starter.class);

    public static void main(String[] args) {
        checkUpdates();
        Properties properties = loadProperties();
        ServerConfiguration config = createConfiguration(properties);
        startServer(config);
    }

    private static void startServer(ServerConfiguration config) {
        ServerLifeCycle server = new HallServer(config);

        ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread serverThread = new Thread(r);
                serverThread.setName("Hall-Server");
                serverThread.setDaemon(false);
                return serverThread;
            }
        });

        Future<?> future = executorService.submit(new ServerThread(server, config));
        try {
            future.get();
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);

        } catch (ExecutionException e) {
            logger.error(e.getMessage(), e);
        }

    }

    private static ServerConfiguration createConfiguration(Properties properties) {
        ServerConfiguration config = new HallServerConfig();
        config.load(properties);
        return config;
    }

    private static Properties loadProperties() {
        logger.debug("trying load properties from {} file", "server.properties");
        Properties properties = new Properties();
        try {
            properties.load(Starter.class.getResourceAsStream("/server.properties"));
        } catch (IOException e) {
            logger.error("Cannot load properties from file: server.properties", e);
        }
        logger.debug("Load properties: {}", properties.toString());
        return properties;
    }

    private static void checkUpdates() {

    }

    private static class ServerThread implements Runnable {
        private ServerLifeCycle server;
        private ServerConfiguration config;

        private ServerThread(ServerLifeCycle server, ServerConfiguration config) {
            this.server = server;
            this.config = config;
        }

        @Override
        public void run() {
            logger.info("Starting server: {} with config: {}", server, config);
            server.init(config);
            server.start();
            logger.info("Stopping server: {} with config: {}", server, config);
        }
    }
}
